/*
 * Ext JS Library 2.2
 * Copyright(c) 2006-2008, Ext JS, LLC.
 * licensing@extjs.com
 * 
 * http://extjs.com/license
 */
Ext.onReady(function() {
    var paper_id = -1;
    var papers_store = new Ext.data.GroupingStore({
        remoteSort: true,
        groupField: 'area_short',
        sortInfo: {
            field: 'id',
            direction: 'ASC'
        },
        proxy: new Ext.data.HttpProxy({
            url: 'reviewedpapers'
        }),
        reader: new Ext.data.JsonReader({
            root: 'papers',
            totalProperty: 'totalCount',
            id: 'id'
        },
        [{
            name: 'id'
        },
        {
            name: 'title'
        },
        {
            name: 'authors'
        },
        {
            name: 'abstract'
        },
        {
            name: 'date_sent'
        },
        {
            name: 'status_id'
        },
        {
            name: 'isAccepted',
            type: 'bool'
        },
        {
            name: 'file_pdf'
        },
        {
            name: 'file_doc'
        },
        {
            name: 'file_size_pdf'
        },
        {
            name: 'file_size_doc'
        },
        {
            name: 'category_name_en'
        },
        {
            name: 'area_name_en'
        },
        {
            name: 'area_short'
        },
        {
            name: 'email'
        }])
    });
    var filters = new Ext.ux.grid.GridFilters({
        filters: [{
            type: 'string',
            dataIndex: 'title'
        },
        {
            type: 'string',
            dataIndex: 'authors'
        },
        {
            type: 'string',
            dataIndex: 'category_name'
        },
        {
            type: 'string',
            dataIndex: 'area_name'
        }]
    });
    /*    var pagingBar = new Ext.PagingToolbar({
        pageSize: 25,
        store: ds,
        displayInfo: true,
        displayMsg: 'Displaying papers {0} - {1} of {2}',
        emptyMsg: "No papers to display"
    });*/
    function renderReviewer(value, p, r) {
        var yes = '<img src="../images/2.jpg">';
        var no = '<img src="../images/1.jpg">';
        if (value) {
            return yes;
        } else {
            return no;
        }
    }
    function renderDownload(value, p, r) {
        var str = '';
        var img_pdf = '<img src="../images/pdf.png">&nbsp;';
        var img_doc = '<img src="../images/doc.png">&nbsp;';
        var pdf = r.data['file_pdf'];
        var doc = r.data['file_doc'];
        if (pdf != '') {
            str += String.format('<div><a href="paper/download/?id={0}&ft=pdf">{2}</a><a href="paper/download/?id={0}&ft=pdf">{1}</a> {3} KB</div>', value, pdf, img_pdf, r.data['file_size_pdf']);
        }
        if (doc != '') {
            str += String.format('<div><a href="paper/download/?id={0}&ft=doc">{2}</a><a href="paper/download/?id={0}&ft=doc">{1}</a> {3} KB</div>', value, doc, img_doc, r.data['file_size_doc']);
        }
        return str;
    } // create the grid
    var papers_grid = new Ext.grid.GridPanel({
        store: papers_store,
        columns: [{
            header: "Title",
            width: 350,
            dataIndex: 'title',
            sortable: true
        },
        {
            header: "Area",
            width: 50,
            dataIndex: 'area_short',
            sortable: true
        }],
        view: new Ext.grid.GroupingView({
            forceFit: true,
            groupTextTpl: '{text} ({[values.rs.length]} {[values.rs.length > 1 ? "Papers" : "Paper"]})'
        }),
        plugins: filters,
        renderTo: 'papers-grid',
        width: 400,
        height: 600,
        title: 'Papers',
        frame: true,
        loadMask: true
    });
    papers_grid.on('rowclick',
    function(grid, rowIndex, e) {
        var record = papers_store.getAt(rowIndex);
        paper_id = record.id;
        Ext.getCmp('status').setValue(record.data.status_id);
        var detailPanel = Ext.getCmp('paperDetailPanel');
        if (record.data.file_pdf != '') {
            download_pdf = '<a href="../paper/download/?id={id}&ft=pdf"><img src="../../images/pdf.png"></a><a href="../paper/download/?id={id}&ft=pdf">{file_pdf}</a>&nbsp;';
        } else {
            download_pdf = '';
        }
        if (record.data.file_doc != '') {
            download_doc = '<a href="../paper/download/?id={id}&ft=doc"><img src="../../images/doc.png"></a><a href="../paper/download/?id={id}&ft=doc">{file_doc}</a>';
        } else {
            download_doc = '';
        }
        var paperTplMarkup = ['<table>', '<tr><td valign="top"><b>Title:</b></td><td>{title}</td></tr>', '<tr><td valign="top"><b>Authors:</b></td><td>{authors}</td></tr>', '<tr><td valign="top"><b>Corespondence:</b></td><td><a href="mailto:{email}">{email}</a></td></tr>', '<tr><td valign="top"><b>Download:</b></td><td>' + download_pdf + download_doc + '</td></tr>', '<tr><td valign="top"><b>Area:</b></td><td>{area_name_en}</td></tr>', '<tr><td valign="top"><b>Category:</b></td><td>{category_name_en}</td></tr>', '<tr><td valign="top"><b>Abstract:</b></td><td>{abstract}</td></tr>', '</table>'];
        var paperTpl = new Ext.Template(paperTplMarkup);
        paperTpl.overwrite(detailPanel.body, record.data);
    });
    var paper_status_store = new Ext.data.Store({
        proxy: new Ext.data.HttpProxy({
            url: '../paperstatus/all'
        }),
        reader: new Ext.data.JsonReader({
            root: 'statuses',
            totalProperty: 'totalCount',
            id: 'id'
        },
        [{
            name: 'id'
        },
        {
            name: 'name_mk'
        },
        {
            name: 'name_en'
        },
        {
            name: 'description'
        }])
    });
    paper_status_store.load();
    var ct = new Ext.Panel({
        renderTo: 'paper-details',
        frame: true,
        title: 'Paper details',
        width: 600,
        height: 300,
        layout: 'border',
        items: [{
            id: 'paperDetailPanel',
            height: 220,
            region: 'center',
            bodyStyle: {
                background: '#ffffff',
                padding: '7px'
            },
            html: ''
        },
        {
            xtype: 'fieldset',
            id: 'fs',
            title: 'Set paper status',
            height: 80,
            width: 500,
            region: 'south',
            labelWidth: 80,
            items: [new Ext.form.ComboBox({
                fieldLabel: 'Paper status',
                id: 'status',
                hiddenName: 'status_id',
                store: paper_status_store,
                valueField: 'id',
                displayField: 'name_en',
                typeAhead: true,
                mode: 'local',
                triggerAction: 'all',
                emptyText: 'Select status...',
                selectOnFocus: true,
                forseSelection: true,
                editable: false,
                width: 190
            })]
        }],
        bbar: [{
            text: 'View reviews',
            handler: function() {
                reviews_store.load({
                    params: {
                        paper_id: paper_id
                    },
                    callback: function() {
                        Ext.getCmp('detailPanel').setVisible(false);
                    }
                });
            },
            waitMsg: 'Loading reviews...',
            tooltip: 'Select papers and click to view reviews'
        },
        {
            text: 'Save status',
            type: 'submit',
            name: 'login',
            handler: function() {
                var status_id = Ext.getCmp('status').getValue();
                Ext.Ajax.request({
                    url: 'updatestatus',
                    success: function() {
                        Ext.Msg.alert('Information', 'Paper status updated successfully');
                        papers_store.load();
                    },
                    params: {
                        paper_id: paper_id,
                        status_id: status_id
                    }
                });
            }
        }]
    });
    var reviews_store = new Ext.data.Store({
        proxy: new Ext.data.HttpProxy({
            url: '../review/getreviews'
        }),
        reader: new Ext.data.JsonReader({
            root: 'reviews',
            totalProperty: 'totalCount',
            id: 'id'
        },
        [{
            name: 'id'
        },
        {
            name: 'first_name'
        },
        {
            name: 'last_name'
        },
        {
            name: 'comment'
        },
        {
            name: 'conf_comment'
        },
        {
            name: 'theory_grade'
        },
        {
            name: 'practice_grade'
        },
        {
            name: 'overview_grade'
        },
        {
            name: 'grade'
        },
        {
            name: 'date_reviewed',
            type: 'date',
            dateFormat: 'Y-m-d G:i:s'
        },
        {
            name: 'date_assigned',
            type: 'date',
            dateFormat: 'Y-m-d G:i:s'
        },
        {
            name: 'date_downloaded',
            type: 'date',
            dateFormat: 'Y-m-d G:i:s'
        }])
    });
    function renderGrade(value, p, r) {
        return String.format('{0} - <b>{1}</b>', grade_desc[value], value);
    }
    function renderOveralGrade(value, p, r) {
        return String.format('{0} - <b>{1}</b>', o_grade_desc[value], value);
    } // create the grid
    var reviews_grid = new Ext.grid.GridPanel({
        store: reviews_store,
        columns: [{
            header: lbl_theory,
            width: 150,
            dataIndex: 'theory_grade',
            sortable: true,
            renderer: renderGrade
        },
        {
            header: lbl_practice,
            width: 150,
            dataIndex: 'practice_grade',
            sortable: true,
            renderer: renderGrade
        },
        {
            header: lbl_overview,
            width: 100,
            dataIndex: 'overview_grade',
            sortable: false,
            renderer: renderGrade
        },
        {
            header: lbl_grade,
            width: 200,
            dataIndex: 'grade',
            sortable: true,
            renderer: renderOveralGrade
        }],
        sm: new Ext.grid.RowSelectionModel({
            singleSelect: true
        }),
        viewConfig: {
            forceFit: true
        },
        split: true,
        region: 'north',
        width: 600,
        height: 100,
        loadMask: true
    });
    var ct = new Ext.Panel({
        renderTo: 'reviews-grid',
        frame: true,
        title: lbl_reviews,
        width: 600,
        height: 500,
        layout: 'border',
        items: [reviews_grid, {
            id: 'detailPanel',
            hidden: true,
            region: 'center',
            bodyStyle: {
                background: '#ffffff',
                padding: '7px'
            },
            html: lbl_details
        }]
    });
    reviews_grid.getSelectionModel().on('rowselect',
    function(sm, rowIdx, r) {
        var detailPanel = Ext.getCmp('detailPanel');
        detailPanel.setVisible(true);
        var date_reviewed = new Date(r.data.date_reviewed);
        var date_assigned = new Date(r.data.date_assigned);
        var date_downloaded_str = 'Not downloaded';
        if (r.data.date_downloaded != '') {
            date_downloaded_str = new Date(r.data.date_downloaded).format('j F, Y H:i:s');
        }
        var reviewerTplMarkup = ['<table>', '<tr><th><b>Reviewer Name:</b></th><td>{first_name} {last_name}</td></tr>', '<tr><th><b>Date reviewed:</b></th><td>' + date_reviewed.format('j F, Y H:i:s') + '</td></tr>', '<tr><th><b>Date assigned:</b></th><td>' + date_assigned.format('j F, Y H:i:s') + '</td></tr>', '<tr><th><b>Date downloaded:</b></th><td>' + date_downloaded_str + '</td></tr>', '<tr><th><b>Scientific comment:</b></th><td>{comment}</td></tr>', '<tr><th><b>Confident comment:</b></th><td>{conf_comment}</td></tr>', '</table>'];
        var reviewerTpl = new Ext.Template(reviewerTplMarkup);
        reviewerTpl.overwrite(detailPanel.body, r.data);
    });
    papers_store.load();
});